package com.scalar.chiptrack.sales.actions;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.Address;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.sales.EndUser;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.dao.EndUserDAO;
import com.scalar.chiptrack.sales.forms.EndUserForm;
import com.scalar.chiptrack.users.User;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;

/**
 * Author: Prabhanjan
 * Date: Mar 17, 2004
 * Time: 8:10:58 PM
 */

public class EndUserAction extends ChipTrackAction
{
    private int endUserId = -1;

    private static final String ACTION_NAME = "/endUser.do";

    public ActionForward execute ( ActionMapping mapping,
                                   ActionForm form,
                                   HttpServletRequest request,
                                   HttpServletResponse response )
            throws Exception
    {

        String action = request.getParameter ( "action" );
		//System.out.println("Subform action  " + action);
		
        EndUserForm subform = ( EndUserForm ) form;

        HttpSession session = request.getSession ();
        User user = ( User ) session.getAttribute ( SessionKeys.USER_KEY );

        if ( user == null )
        {
            session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString () );
            return ( mapping.findForward ( "login" ) );
        }

        HashMap info = new LinkedHashMap ();
        request.setAttribute ( SessionKeys.INFO_MESSAGES, info );
        HashMap errors = new LinkedHashMap ();
        request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );

        if((action == "")||(action.equals("")) || (action == null) )
        {
        	int endUserId = Integer.parseInt(request.getParameter("endUser.endUserId"));
            session.setAttribute("contactPersonsList",EndUserDAO.getAllContactPersonsForEndUser(Integer.parseInt(request.getParameter("endUser.endUserId"))) );
            session.setAttribute("contactPersonsMap" ,EndUserDAO.getContactPersonDetailsMapForEndUser(Integer.parseInt(request.getParameter("endUser.endUserId"))) );
			
			ArrayList shippingLocs = subform.getEndUser().getShippingLocations();
			int  shippingLocsSize = shippingLocs.size();
			ArrayList contactPersons = new ArrayList();
			HashMap allContactPersons = new HashMap();
			HashMap contactPersonsMap = null;
			
			if(endUserId == -1 )
			{
				if(shippingLocs != null)
				{
					
					for(int aa = 0; aa<shippingLocsSize ; aa++)
					{
						Address address = (Address)shippingLocs.get(aa);
						contactPersons = CustomerDAO.loadContactPersons(address.getLocAddressId());
						address.setContactPersons(contactPersons);
						contactPersonsMap = CustomerDAO.getAddressContactPersonDetailsMap (address.getLocAddressId());
						allContactPersons.put(""+address.getLocAddressId() , contactPersonsMap);
					}
				}
			}
			else
			{
				HashMap cPersons = new HashMap();
				int addId = 0;
				for(int bb = 0 ; bb < shippingLocsSize; bb++)
				{
					Address address = (Address)shippingLocs.get(bb);
					if( address.getAddressId() == -1)
					{
						addId = address.getLocAddressId();
					}
					else
					{
						addId = address.getAddressId();
					}
					contactPersons = CustomerDAO.loadContactPersons(addId);
						
					address.setContactPersons(contactPersons);
					contactPersonsMap = CustomerDAO.getAddressContactPersonDetailsMap (addId);
					cPersons.put(""+addId , contactPersonsMap);
					allContactPersons.putAll(cPersons);

				}
			}
			if( endUserId == -1)
			{
				session.setAttribute ( "billingContactPersonsList", CustomerDAO.getAllContactPersonsForAddress( subform.getEndUser().getBillAddressId()) );
				session.setAttribute ( "billingContactPersonsMap", CustomerDAO.getAddressContactPersonDetailsMap ( subform.getEndUser().getBillAddressId() ) );
				session.setAttribute ( "shippingContactPersonsList", CustomerDAO.getAllContactPersonsForAddress( subform.getEndUser().getShipAddressId() ) );
				session.setAttribute ( "shippingContactPersonsMap", CustomerDAO.getAddressContactPersonDetailsMap ( subform.getEndUser().getShipAddressId() ) );
				session.setAttribute ( "allShippingContactPersonsMap", allContactPersons );
			}
			else
			{
				session.setAttribute ( "billingContactPersonsList", CustomerDAO.getAllContactPersonsForAddress( Integer.parseInt ( request.getParameter ( "endUser.defaultBillingAddressId" ) ) ) );
				session.setAttribute ( "billingContactPersonsMap", CustomerDAO.getAddressContactPersonDetailsMap ( Integer.parseInt ( request.getParameter ( "endUser.defaultBillingAddressId" ) ) ) );
				session.setAttribute ( "shippingContactPersonsList", CustomerDAO.getAllContactPersonsForAddress( Integer.parseInt ( request.getParameter ( "endUser.defaultShippingAddressId" ) ) ) );
				session.setAttribute ( "shippingContactPersonsMap", CustomerDAO.getAddressContactPersonDetailsMap ( Integer.parseInt ( request.getParameter ( "endUser.defaultShippingAddressId" ) ) ) );
				session.setAttribute ( "allShippingContactPersonsMap", allContactPersons );
			}
           

            return (mapping.findForward("success"));
        }


        if ( "CreateEndUser".equals ( action ) )
        {
            EndUser endUser = new EndUser();
            ArrayList shippingList = new ArrayList();
			Address shippingAddress = new Address();
            shippingList.add(shippingAddress);
            endUser.setShippingLocations(shippingList);
            endUser.setCustomerId(Integer.parseInt(request.getParameter("customerId")));
            subform.setEndUser(endUser);

            subform.setAction(action);

            session.setAttribute ( "contactPersonsList", new ArrayList () );
            session.setAttribute ( "contactPersonsMap", new HashMap () );
			session.setAttribute ( "billingContactPersonsList", CustomerDAO.getAllContactPersonsForAddress( endUser.getBillAddressId() ) );
			session.setAttribute ( "billingContactPersonsMap", CustomerDAO.getAddressContactPersonDetailsMap ( endUser.getBillAddressId()) );
			session.setAttribute ( "shippingContactPersonsList", CustomerDAO.getAllContactPersonsForAddress( endUser.getShipAddressId() ) );
			session.setAttribute ( "shippingContactPersonsMap", CustomerDAO.getAddressContactPersonDetailsMap ( endUser.getShipAddressId() ) );
			session.setAttribute ( "allShippingContactPersonsMap", EndUserDAO.getAllContactPersonsForEndUserShippingLocations ( endUser.getEndUserId() ) );
			
            
        }
        else if ( "EditEndUser".equals ( action ) )
        {
            EndUser endUser = EndUserDAO.getEndUserDetails(Integer.parseInt(request.getParameter("endUserId")));
            session.setAttribute("contactPersonsList",EndUserDAO.getAllContactPersonsForEndUser(Integer.parseInt(request.getParameter("endUserId"))) );
            session.setAttribute("contactPersonsMap" ,EndUserDAO.getContactPersonDetailsMapForEndUser(Integer.parseInt(request.getParameter("endUserId"))) );
			session.setAttribute ( "billingContactPersonsList", CustomerDAO.getAllContactPersonsForAddress( endUser.getDefaultBillingAddressId() ) );
			session.setAttribute ( "billingContactPersonsMap", CustomerDAO.getAddressContactPersonDetailsMap ( endUser.getDefaultBillingAddressId()) );
			session.setAttribute ( "shippingContactPersonsList", CustomerDAO.getAllContactPersonsForAddress( endUser.getDefaultShippingAddressId() ) );
			session.setAttribute ( "shippingContactPersonsMap", CustomerDAO.getAddressContactPersonDetailsMap ( endUser.getDefaultShippingAddressId() ) );
			session.setAttribute ( "allShippingContactPersonsMap", EndUserDAO.getAllContactPersonsForEndUserShippingLocations ( endUser.getEndUserId() ) );
            

            subform.setEndUser(endUser);
            subform.setAction(action);
        }
        if("SaveEndUser".equals(action))
        {
            EndUser endUser = subform.getEndUser();
            endUser.setEndUserName(endUser.getEndUserName().trim());

            endUserId = -1;
            boolean success = false;
            DBTransaction dbTransaction = null;

            if(!isTokenValid(request))
            {
                errors.put("This End User details are already saved, to change it visit End User details screen ","");
            }
            //resetToken(request);

            if(!errors.isEmpty())
            {
                request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
                //saveToken(request);
                return (mapping.findForward("success"));
            }

            if ( endUser.getEndUserId () == -1 )
            {
                if ( EndUserDAO.isEndUserExists ( subform.getEndUser ().getEndUserName ().trim (), endUser.getCustomerId(), 1, "NewEndUser" ) )
                {
                    errors.put ( "End User", "End User Name Already exists, Please enter new name" );
                    request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
                    subform.setAction ( "CreateEndUser" );

                    session.setAttribute ( "contactPersonsList", new ArrayList () );
                    session.setAttribute ( "contactPersonsMap", new HashMap () );
					session.setAttribute ( "billingContactPersonsList", CustomerDAO.getAllContactPersonsForAddress( endUser.getBillAddressId() ) );
					session.setAttribute ( "billingContactPersonsMap", CustomerDAO.getAddressContactPersonDetailsMap ( endUser.getBillAddressId()) );
					session.setAttribute ( "shippingContactPersonsList", CustomerDAO.getAllContactPersonsForAddress( endUser.getShipAddressId() ) );
					session.setAttribute ( "shippingContactPersonsMap", CustomerDAO.getAddressContactPersonDetailsMap ( endUser.getShipAddressId() ) );
					
					ArrayList shippingLocs = subform.getEndUser().getShippingLocations();
					ArrayList contactPersons = new ArrayList();
					HashMap allContactPersons = new HashMap();
					HashMap contactPersonsMap = null;
					
					if(shippingLocs != null)
					{
					   int shippingLocsSize = shippingLocs.size();
						for(int aa = 0; aa<shippingLocsSize ; aa++)
						{
							Address address = (Address)shippingLocs.get(aa);
							contactPersons = CustomerDAO.loadContactPersons(address.getLocAddressId());
							address.setContactPersons(contactPersons);
							contactPersonsMap = CustomerDAO.getAddressContactPersonDetailsMap (address.getLocAddressId());
							allContactPersons.put(""+address.getLocAddressId() , contactPersonsMap);
						}
					}
					session.setAttribute ( "allShippingContactPersonsMap", allContactPersons );
                    //saveToken ( request );
                    return mapping.findForward ( "success" );
                }
            }
            else
            {
                //Added by KumaraSwamy on Oct 15th, 2004 for not allowing the duplicate End user when editing the End uesr.
                if ( EndUserDAO.isEndUserExists ( subform.getEndUser ().getEndUserName ().trim (), endUser.getCustomerId(), endUser.getEndUserId(), "ExistingEndUser" ) )
                {
                    errors.put ( "End User", "End User Already Exists with the Name "+subform.getEndUser ().getEndUserName ().trim () );
                    request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
                }
                if(!errors.isEmpty())
                {
                    request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
                    return (mapping.findForward("success"));
                }
            }
            try
            {
                dbTransaction = DBTransaction.getInstance ();
                dbTransaction.begin ();

                if ( endUser.getEndUserId () == -1 )
                {
                    endUserId = EndUserDAO.saveEndUserDetails ( dbTransaction, endUser );

                    EndUserDAO.updateEndUserContactPerson( dbTransaction , endUserId );
                    EndUserDAO.updatePartNumberEndUserIds ( dbTransaction, endUserId );
					CustomerDAO.updateAddressContactPerson ( dbTransaction, endUser.getDefaultBillingAddressId(),endUser.getBillAddressId() );
					CustomerDAO.updateAddressContactPerson ( dbTransaction, endUser.getDefaultShippingAddressId(),endUser.getShipAddressId() );
                    
                    subform.getEndUser ().setEndUserId ( endUserId );
                }
                else
                {
                    endUserId = EndUserDAO.saveEndUserDetails ( dbTransaction, endUser );
                }

                if ( endUserId != -1 )
                    success = true;



            }
            catch (ScalarException se)
            {
	            se.printStackTrace();
            }
            finally
            {
                if (success == true)
                {
                    dbTransaction.commit();

                    info.put("End User", "Saved Successfully");
                    //info.put("View/Print ","Click here to <a href='javascript:openCustomer();'> view/print </a>Customer Details");
                }
                else
                {
                    dbTransaction.rollback();
                    errors.put(ERROR_INTERNAL_SERVER_ERROR, "Could not save End User");
                    errors.put( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                    session.setAttribute( SessionKeys.ERROR_REPORT_SUBJECT, " Error: Could Not Save EndUser ");
                    session.setAttribute( SessionKeys.ERROR_REPORT, null );
                }
            }
            if(!info.isEmpty())
            request.setAttribute(SessionKeys.MESSAGES, info);
            EndUser endUserNew = EndUserDAO.getEndUserDetails(endUser.getEndUserId());
            subform.setEndUser(endUserNew);

            session.setAttribute("contactPersonsList",EndUserDAO.getAllContactPersonsForEndUser(endUser.getEndUserId()));
            session.setAttribute("contactPersonsMap" ,EndUserDAO.getContactPersonDetailsMapForEndUser( endUser.getEndUserId() ));
			session.setAttribute ( "billingContactPersonsList", CustomerDAO.getAllContactPersonsForAddress( endUser.getDefaultBillingAddressId() ) );
			session.setAttribute ( "billingContactPersonsMap", CustomerDAO.getAddressContactPersonDetailsMap ( endUser.getDefaultBillingAddressId()) );
			session.setAttribute ( "shippingContactPersonsList", CustomerDAO.getAllContactPersonsForAddress( endUser.getDefaultShippingAddressId() ) );
			session.setAttribute ( "shippingContactPersonsMap", CustomerDAO.getAddressContactPersonDetailsMap ( endUser.getDefaultShippingAddressId() ) );
			session.setAttribute ( "allShippingContactPersonsMap", EndUserDAO.getAllContactPersonsForEndUserShippingLocations ( endUserNew.getEndUserId() ) );
			
            
            //saveToken ( request );
        }
        return mapping.findForward ( "success" );
    }
}
